﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PdfSharp;
using PdfSharp.Drawing;
using PdfSharp.Pdf;
using System.Diagnostics;
using MigraDoc.DocumentObjectModel;
using MigraDoc.DocumentObjectModel.Tables;
using MigraDoc.Rendering;

namespace Bet_Yatziv
{
    public partial class Rentals : Form
    {
        int roomNumber = 0;
        int idNum = 0;
        int daysNum = 0;
        int billNum = 0;
        string fullname;
        int totalRevenue = 0;

        public Rentals()
        {
            InitializeComponent();
            DataTable renta = DataAccessLayer.GetAllOrders();
            dataGridView1.DataSource = renta;
            refresh();
        }

        //exits
        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        //loading table
        private void Bload_Click(object sender, EventArgs e)
        {
            DataTable table = DataAccessLayer.GetAllOrders();
            dataGridView1.DataSource = table;
            if (table.Rows.Count == 0)
                MessageBox.Show("אין השכרות פעילות");
        }

        //clearing table
        private void Bclear_Click(object sender, EventArgs e)
        {
            dataGridView1.DataSource = null;
            clearAll();
        }

        //add a rental
        private void Badd_Click(object sender, EventArgs e)
        {
            //     try
            //     {
            string roomNum = txt_roomNum.Text;
            string id = txt_costID.Text;
            DateTime date = txt_date.Value.Date;
            string totalDays = txt_days.Text;
            string bill = txt_bill.Text;
            string type = txt_type.Text;


            roomNumber = convert(txt_roomNum, roomNum, "אין אפשרות להמיר מספר חדר");
            idNum = convert(txt_costID, id, "אין אפשרות להמיר מספר תעודת זהות");
            daysNum = convert(txt_days, totalDays, "ערך הימים חייב להיות מספר");
            billNum = convert(txt_bill, bill, "ערך החשבון חייב להיות ערך מספרי");

            DataAccessLayer.AddNewRent(roomNumber, idNum, roomNumber, daysNum, date);
            string query1 = "select * from tbl_rooms";
            DataTable dt1 = AdoHelper.ExecuteDataTable(query1);
            fullname = txt_fname.Text + txt_lname.Text;


            for (int i = 0; i < dt1.Rows.Count; i++)
                if ((int)(dt1.Rows[i].ItemArray[0]) == roomNumber)
                {
                    DataAccessLayer.UpdateStat(roomNumber, false);
                    updateBC(roomNumber, txt_roomNum, txt_retRoomNum);
                    MessageBox.Show("החדר הושכר בהצלחה", "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    /*refresh();*/
                }


            totalRevenue = totalRevenue + billNum;
            /***PDF***/
            /* start */
            Document document = new Document();
            MigraDoc.DocumentObjectModel.Section section = document.AddSection();
            MigraDoc.DocumentObjectModel.Paragraph paragraph = section.AddParagraph();
            //paragraph.AddImage(@"\BEIT YATZIV logo.png");
            MigraDoc.DocumentObjectModel.FormattedText ft = paragraph.AddFormattedText("Order Detailes\n", TextFormat.Bold);
            ft.Font.Size = 30;
            paragraph.AddFormattedText("\n\n\n\n");
            ft = paragraph.AddFormattedText("Room number:", TextFormat.Underline);
            ft.Font.Size = 14;
            ft = paragraph.AddFormattedText(roomNum, TextFormat.Bold);
            ft.Font.Size = 14;
            ft = paragraph.AddFormattedText("\nRoom type:", TextFormat.Underline);
            ft.Font.Size = 14; 
            ft = paragraph.AddFormattedText(type, TextFormat.Bold);
            ft.Font.Size = 14; 
            ft = paragraph.AddFormattedText("\nBeds in this room:", TextFormat.Underline);
            ft.Font.Size = 14; 
            ft = paragraph.AddFormattedText(txt_bedAmount.Text, TextFormat.Bold);
            ft.Font.Size = 14; 
            ft = paragraph.AddFormattedText("\nPrice for a day:", TextFormat.Underline);
            ft.Font.Size = 14; 
            ft = paragraph.AddFormattedText(txt_price.Text + "$", TextFormat.Bold);
            ft.Font.Size = 14; 
            ft = paragraph.AddFormattedText("\nCheck-In day:", TextFormat.Underline);
            ft.Font.Size = 14; 
            ft = paragraph.AddFormattedText(txt_date.Text, TextFormat.Bold);
            ft.Font.Size = 14; 
            ft = paragraph.AddFormattedText("\nDays:", TextFormat.Underline);
            ft.Font.Size = 14; 
            ft = paragraph.AddFormattedText(txt_days.Text, TextFormat.Bold);
            ft.Font.Size = 14; 
            ft = paragraph.AddFormattedText("\nTotal price:", TextFormat.Underline);
            ft.Font.Size = 14; 
            ft = paragraph.AddFormattedText(txt_bill.Text + "$", TextFormat.Bold);
            ft.Font.Size = 14; 
            paragraph = section.AddParagraph();
            ft = paragraph.AddFormattedText("\nClient:");
            ft.Font.Size = 20;
            ft = paragraph.AddFormattedText(fullname, TextFormat.Bold);
            ft.Font.Size = 20;
            ft = paragraph.AddFormattedText("\nClient ID:");
            ft.Font.Size = 20;
            ft = paragraph.AddFormattedText(id, TextFormat.Italic);
            ft.Font.Size = 20;
            paragraph = section.AddParagraph();
            paragraph.AddFormattedText("\n\n\n\n\n\n\n\n");
            paragraph.AddFormattedText("Sign here");
            string emptyLine = ":\t\t\t\t";
            paragraph.AddFormattedText(emptyLine,TextFormat.Underline);
            DateTime today = DateTime.Today;
            paragraph.AddFormattedText("\t\t\tDate of signing");
            paragraph.AddFormattedText(today.ToString("dd/MM/yyyy"));

            /* End */
            PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer(false,
            PdfFontEmbedding.Always);
            pdfRenderer.Document = document;
            pdfRenderer.RenderDocument();
            string filename = id+".pdf";
            pdfRenderer.PdfDocument.Save(filename);
            Process.Start(filename);
            refresh();
            //  }
            //   catch
            //    {
            //        MessageBox.Show("אנא מלא את כל הפרטים לפני שתוכל להשכיר חדר", "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //   }
        }

        //updates the room details when the employee chooses a room
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string roomNum = txt_roomNum.Text;
            if (roomNum == "")
                txt_days.Enabled = false;
            txt_days.Enabled = true;
            int i = 0;
            string query1 = "select * from tbl_rooms";
            DataTable dt1 = AdoHelper.ExecuteDataTable(query1);

            int roomNumber = 0;
            roomNumber = convert(txt_roomNum, roomNum, "אין אפשרות להמיר מספר חדר");

            for (i = 0; i < dt1.Rows.Count; i++)
                if ((Boolean)(dt1.Rows[i].ItemArray[4]) == true)
                    if (roomNumber == (int)(dt1.Rows[i].ItemArray[0]))
                        break;

            txt_type.Text = "" + dt1.Rows[i].ItemArray[1];
            txt_bedAmount.Text = "" + dt1.Rows[i].ItemArray[3];
            txt_price.Text = "" + dt1.Rows[i].ItemArray[2];
        }

        //refreshing info
        private void refresh()
        {
            dataGridView1.DataSource = null;
            DataTable dt = DataAccessLayer.GetAllOrders();
            dataGridView1.DataSource = dt;
            clearAll();

            txt_roomNum.Items.Clear();
            txt_costID.Items.Clear();
            txt_retRoomNum.Items.Clear();

            //bringing all the room numbers
            DataTable table = DataAccessLayer.GetAllRooms();
            string query1 = "select * from tbl_rooms";
            DataTable dt1 = AdoHelper.ExecuteDataTable(query1);
            for (int i = 0; i < dt1.Rows.Count; i++)
                if ((Boolean)(dt1.Rows[i].ItemArray[4]) == true)
                    txt_roomNum.Items.Add(dt1.Rows[i].ItemArray[0]);
                else if ((Boolean)(dt1.Rows[i].ItemArray[4]) == false)
                    txt_retRoomNum.Items.Add(dt1.Rows[i].ItemArray[0]);

            //bringing all the costumers id's
            DataTable cost = DataAccessLayer.GetAllCostumers();
            string query2 = "select costumerID from tbl_costumers";
            DataTable dt2 = AdoHelper.ExecuteDataTable(query2);
            for (int i = 0; i < dt2.Rows.Count; i++)
                txt_costID.Items.Add(dt2.Rows[i].ItemArray[0]);

        }

        //calculating bill
        private void txt_days_TextChanged(object sender, EventArgs e)
        {
            if (txt_roomNum.Text != "")
                if (txt_days.Text == "")
                    txt_bill.Text = "0";
                else
                {
                    int i = 0;
                    DataTable table = DataAccessLayer.GetAllRooms();
                    string query1 = "select * from tbl_rooms";
                    DataTable dt1 = AdoHelper.ExecuteDataTable(query1);
                    int licNum = 0;

                    //converting days
                    if (txt_days.Text.Length > 0)
                    {
                        try
                        {
                            licNum = Convert.ToInt32(txt_roomNum.Text);
                        }
                        catch (FormatException exp)
                        {
                            MessageBox.Show(exp.Message + "אין אפשרות להמיר את הערך", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            txt_roomNum.Text = "";
                            return;
                        }
                    }

                    for (i = 0; i < dt1.Rows.Count; i++)
                        if (licNum == (int)(dt1.Rows[i].ItemArray[0]))
                            break;

                    int daysNum = 0;
                    if (txt_days.Text.Length > 0)

                        try
                        {
                            daysNum = Convert.ToInt32(txt_days.Text);
                        }
                        catch (FormatException exp)
                        {
                            MessageBox.Show(exp.Message + "אין אפשרות להמיר את הערך", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            txt_days.Text = "";
                            return;
                        }
                    txt_bill.Text = "" + daysNum * (int)(dt1.Rows[i].ItemArray[2]);
                }
        }

        //selecting costumer id
        private void txt_costID_SelectedIndexChanged(object sender, EventArgs e)
        {
            int i = 0;
            string query1 = "select * from tbl_costumers";
            DataTable dt1 = AdoHelper.ExecuteDataTable(query1);

            int idNum = 0;
            if (txt_costID.Text.Length > 0)

                try
                {
                    idNum = Convert.ToInt32(txt_costID.Text);
                }
                catch (FormatException exp)
                {
                    MessageBox.Show(exp.Message + "אין אפשרות להמיר את הערך", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txt_costID.Text = "";
                    return;
                }

            for (i = 0; i < dt1.Rows.Count; i++)
                if (idNum == (int)(dt1.Rows[i].ItemArray[0]))
                    break;

            txt_fname.Text = "" + dt1.Rows[i].ItemArray[1];
            txt_lname.Text = "" + dt1.Rows[i].ItemArray[2];
        }

        //returning a room
        private void rentReturn_Click(object sender, EventArgs e)
        {
            string room = txt_retRoomNum.Text;
            //converting room number to int
            int roomNum = 0;

            try
            {
                roomNum = Convert.ToInt32(txt_retRoomNum.Text);
            }
            catch (FormatException exp)
            {
                MessageBox.Show(exp.Message + "מספר החדר חייב להיות מספר", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txt_retRoomNum.Text = "";
                return;
            }

            string query1 = "select * from tbl_rooms";
            DataTable dt1 = AdoHelper.ExecuteDataTable(query1);
            for (int i = 0; i < dt1.Rows.Count; i++)
                if ((int)(dt1.Rows[i].ItemArray[0]) == roomNum)
                {
                    DataAccessLayer.UpdateStat(roomNum, true);
                    DataAccessLayer.DeleteOrder(roomNum);
                    updateBC(roomNum, txt_retRoomNum, txt_roomNum);
                    MessageBox.Show("החדר הוחזר בהצלחה", "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    refresh();
                }
        }

        //updating comboboxes
        private void updateBC(int room, ComboBox combS, ComboBox combT)
        {
            for (int i = 0; i < combS.Items.Count; i++)
            {
                if (room == (int)(combS.Items[i]))
                {
                    combT.Items.Add(combS.Items[i]);
                    combS.Items.Remove(combS.Items[i]);
                }
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Hide();
            Costumers cost = new Costumers();
            cost.ShowDialog();
            this.Show();
            refresh();
        }

        //clearing all text boxes
        private void clearAll()
        {
            txt_price.Text = txt_fname.Text = txt_bedAmount.Text = txt_lname.Text = txt_type.Text = "";
            txt_retRoomNum.Text = txt_roomNum.Text = "";
            txt_costID.Text = txt_date.Text = txt_days.Text = txt_bill.Text = "";
        }

        //converting to int
        private int convert(ComboBox box, string text, string error)
        {
            int ans = -1;
            if (text.Length > 0)
            {

                try
                {
                    ans = Convert.ToInt32(text);
                }
                catch (FormatException exp)
                {
                    MessageBox.Show(exp.Message + "" + error + "", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    box.Text = "";
                }

            }
            return ans;
        }

        //converting to int
        private int convert(TextBox box, string text, string error)
        {
            int ans = -1;
            if (text.Length > 0)
            {

                try
                {
                    ans = Convert.ToInt32(text);
                }
                catch (FormatException exp)
                {
                    MessageBox.Show(exp.Message + "" + error + "", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    box.Text = "";
                }

            }
            return ans;
        }

        //checking for available rooms for rental
        private void button4_Click(object sender, EventArgs e)
        {
            string query = "Select * from tbl_rooms where (((tbl_rooms.available)=True));";
            DataTable dt = AdoHelper.ExecuteDataTable(query);
            dataGridView1.DataSource = dt;

            if (dt.Rows.Count == 0)
                MessageBox.Show("אין חדרים זמינים להשכרה", "הודעה");
        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            MessageBox.Show("סהכ רווח מאז שהופעלה המערכת: " + totalRevenue, "הודעה");
        }

        private void button3_Click(object sender, EventArgs e)
        {

            string query = "SELECT * from tbl_orders where (([tbl_orders].[rentDate])=DateValue(Date()))";
            DataTable dt = AdoHelper.ExecuteDataTable(query);
            dataGridView1.DataSource = dt;

            if (dt.Rows.Count == 0)
                MessageBox.Show("אין חדרים מוזמנים היום", "הודעה");
        }
   }
}